vue控制权限问题
后台返回的接口
{
"code": 200,
"data": [{
path: '/',
meta: {
title: '首页',
show: true,
limits: ['test'],
},
},
{
path: '/about',
meta: {
title: '关于',
show: false
},
},
{
path: '/test',
meta: {
title: '测试',
show: true,
},
},
{
path: '/more',
meta: {
title: '更多',
show: true
},
children: [{
path: '/more/navone',
meta: {
title: '更多一',
show: false
},
},
{
path: '/more/navtwo',
meta: {
title: '更多二',
show: true
},
}
]
}
]
}
权限指令
import Vue from 'vue';
import store from '@/store/index'
// v-permission: 功能权限指令
Vue.directive('permission', {
bind(el, binding, vnode, oldVnode) {
const { value } = binding
const limits = store.getters && store.getters.limits
if (value) {
const permissionRoles = value
const hasPermission = limits.some(limit => {
return permissionRoles==limit
})
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error(`need limits! Like v-permission="'test'"`)
}
}
})
vuex操作权限
import {syncRouter, asyncRouter,router } from '@/router/index'
/**
* 递归过滤异步路由表,返回符合用户角色权限的路由表
* @param asyncRouterMap
* @param roles
*/
function filterAsyncRouter(asyncRouter, roles) {
asyncRouter.map((item)=>{
roles.forEach((inItem)=>{
if(item.path==inItem.path){
if(item.redirect){
for(let i=0;i<inItem.children.length;i++){
if(inItem.children[i].meta.show){
item.redirect=inItem.children[i].path;
break;
}
}
}
if(item.children&&inItem.children){
item.children=filterAsyncRouter(item.children,inItem.children)
}
item.meta=inItem.meta;
}
})
})
return asyncRouter;
}
const user = {
state: {
token:'',
routers: syncRouter,
addRouters: [],
limits:[],
},
mutations: {
setToken(state,token){
state.token=token;
},
setAuthInfo(state,theAsyncRouter){
state.addRouters = theAsyncRouter
for(let i=0;i<theAsyncRouter.length;i++){
// syncRouter.push(theAsyncRouter[i]);
router.options.routes.push(theAsyncRouter[i]);
}
router.addRoutes(theAsyncRouter);
state.routers = syncRouter;
console.log(state.routers)
},
setLimits(state,data){
state.limits=data;
}
},
actions: {
setToken({ commit }, token) {
commit('setToken', token)
},
//设置获取的权限信息
setAuthInfo({commit},data){
console.log(data)
let theAsyncRouter = filterAsyncRouter(asyncRouter,data)
commit('setAuthInfo',theAsyncRouter)
},
//设置功能权限
setLimits({commit},data){
commit('setLimits',data);
}
}
}
功能绑定
<el-button type="primary" v-permission="'test'">测试功能显示</el-button>
参考链接:git地址链接
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。